<?php
/**
 * Created by PhpStorm.
 * User: ADMIN
 * Date: 2021/6/3
 * Time: 6:26
 */
namespace app\adminapi\validate;

use app\common\model\Goods;
use app\common\model\GoodsCategory;

class GoodsAdd extends Base
{
    protected $rule = [
        'goods_category_id' => 'require|integer|min:1|dataExists',
        'name' => 'require|onlyRow',
        'price' => 'require|integer|min:1|max:99999999999',
        'num' => 'integer|min:1|max:99999999999',
        'total' => 'integer|min:1|max:99999999999',
        'sold' => 'integer|min:1|max:99999999999',
        'status' => 'statusCorrect',
        'weigh' => 'integer|min:1|max:99999999999',
    ];

    protected $message = [
        'goods_category_id.dataExists' => '分类不存在',

        'name.onlyRow' => '商品已存在',

        'status.statusCorrect' => 'status状态非法',
    ];

    /**
     * 分类是否存在
     * @param $value
     * @param $rule
     * @param $data
     * @return bool
     * @throws \think\exception\DbException
     */
    protected function dataExists($value, $rule, $data)
    {
        if(GoodsCategory::get(['id'=>$value])) return true;
        return false;
    }

    /**
     * 商品名称唯一
     * @param $value
     * @param $rule
     * @param $data
     * @return bool
     * @throws \think\exception\DbException
     */
    protected function onlyRow($value, $rule, $data)
    {
        if(!Goods::get(['name'=>$value])) return true;
        return false;
    }

    protected function statusCorrect($value, $rule, $data)
    {
        $statusArr = ['0', '1'];
        if(in_array($value, $statusArr)) return true;
        return false;
    }

}